package com.elinkway.infinitemovies.view;

import android.app.Activity;
import android.os.Build;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import com.androidquery.AQuery;
import com.baidu.mobad.feeds.BaiduNative;
import com.baidu.mobad.feeds.NativeErrorCode;
import com.baidu.mobad.feeds.NativeResponse;
import com.baidu.mobad.feeds.RequestParameters;
import com.baidu.mobads.SplashAd;
import com.baidu.mobads.SplashAdListener;
import com.elinkway.infinitemovies.listener.MyOnAdListener;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.SelfDataConstant;
import com.elinkway.infinitemovies.selfdata.bean.MyDataRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.utils.AdStatisticsSp;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.le123.ysdq.R;
import com.recyclerlayout.refresh.MyMessageEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;

import static com.umeng.analytics.pro.x.ad;

/**
 * Author: liuxiaojiang(xiao)
 * Date: 2017-04-12
 * Time: 19:12
 * Description: FIXME
 */
public class BaiduNativeAdView {
    private Activity activity;
    private View mView;
    private long startRequestTime = 0;
    private String mAdposition;
    private MyOnAdListener adListener;
    private boolean splashIsResponse = false;
    private boolean isOutTimeJump = false;
    private com.baidu.mobad.feeds.NativeResponse mNativeResponse;

    public MyOnAdListener getAdListener() {
        return adListener;
    }

    public void setAdListener(MyOnAdListener adListener) {
        this.adListener = adListener;
    }

    public BaiduNativeAdView(Activity activity, View view, String mAdposition){
        this.activity = activity;
        this.mView = view;
        this.mAdposition = mAdposition;
    }

    public BaiduNativeAdView(Activity activity, String mAdposition){
        this.activity = activity;
        this.mAdposition = mAdposition;
    }

    public void setBaiduAd(String adId){
        if("splash".equals(mAdposition)){
            startRequestTime = System.currentTimeMillis();
            SplashAdListener listener=new SplashAdListener() {
                @Override
                public void onAdDismissed() {
                    adListener.onAdDismissed();
                }
                @Override
                public void onAdFailed(String arg0) {
                    if(!isOutTimeJump){
                        splashIsResponse = true;
                        reportAdRequestError();
                        adListener.onAdFailed();
                        AdStatisticsSp.savaOneUp(activity, AdStatisticsSp.BAIDUSPLASHADERROR);
                    }
                }
                @Override
                public void onAdPresent() {
                    if(!isOutTimeJump){
                        splashIsResponse = true;
                        reportAdSuccess();
                        reportAdShow();
                        adListener.onAdSuccess(null);
                        AdStatisticsSp.savaOneUp(activity, AdStatisticsSp.BAIDUSPLASHADSUCCESS);
                        AdStatisticsSp.savaOneUp(activity, AdStatisticsSp.BAIDUSPLASHADSHOW);
                    }
                }
                @Override
                public void onAdClick() {
                    reportAdClick();
                }
            };
            new SplashAd(activity, (ViewGroup) mView, listener, adId, true);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(!splashIsResponse){
                        isOutTimeJump = true;
                        adListener.onAdFailed();
                        selfBaiduReport(SelfDataConstant.AC_ADREQUEST_OUTTIME);
                    }
                }
            }, 3000);
            reportAdRequestVtwo();
            AdStatisticsSp.savaOneUp(activity, AdStatisticsSp.BAIDUSPLASHADREQUEST);
        }else{
            BaiduNative baidu = new BaiduNative(activity, adId, new BaiduNative.BaiduNativeNetworkListener() {
                @Override
                public void onNativeFail(NativeErrorCode arg0) {
                    reportAdRequestError();
                }

                @Override
                public void onNativeLoad(List<NativeResponse> arg0) {
                    // 一个广告只允许展现一次，多次展现、点击只会计入一次
                    if (arg0.size() > 0) {
                        reportAdSuccess();
                        // demo仅简单地显示一条。可将返回的多条广告保存起来备用。
                        final NativeResponse nativeResponse = arg0.get(0);
                        mNativeResponse = nativeResponse;
                        if(mView == null){
                            mView = activity.findViewById(R.id.nativeADContainerone);
                        }
                        AQuery aq = new AQuery(activity, mView);
                        mView.setVisibility(View.VISIBLE);
                        if("focus".equals(mAdposition)){
                            aq.id(R.id.ad_text_mark_tv_one).visible();
                            aq.id(R.id.ad_logo_iv).visible();
                            aq.id(R.id.ad_logo_iv).image(nativeResponse.getBaiduLogoUrl(), false, true);
                            aq.id(R.id.focus_item_tv).text(nativeResponse.getTitle());
                            aq.id(R.id.focus_item_image).image(nativeResponse.getImageUrl());
                        } else if ("recom1".equals(mAdposition) || "recom2".equals(mAdposition)) {
                            // 相关推荐
                            aq.id(R.id.relative_item_ad).visible();
                            aq.id(R.id.relative_img_ad_source).visible();
                            aq.id(R.id.relative_img_ad_source).image(nativeResponse.getBaiduLogoUrl(), false, true);
                            aq.id(R.id.relative_img_ad).visible();
                            aq.id(R.id.relative_img_ad).image(nativeResponse.getImageUrl());
                            aq.id(R.id.relative_ad_title).text(nativeResponse.getTitle());
                            aq.id(R.id.relative_ad_desc).text(nativeResponse.getDesc());
                        } else {
                            aq.id(R.id.ad_logo_iv_one).visible();
                            aq.id(R.id.ad_logo_iv_one).image(nativeResponse.getBaiduLogoUrl(), false, true);
                            aq.id(R.id.text_desc_one).text(nativeResponse.getDesc());
                            aq.id(R.id.ad_left_image_iv_one).image(nativeResponse.getImageUrl());
                            aq.id(R.id.text_title_one).text(nativeResponse.getTitle());
                        }
                        // 警告：调用该函数来发送展现，勿漏！
                        nativeResponse.recordImpression(mView);
                        reportAdShow();
                        mView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                // 点击响应
                                nativeResponse.handleClick(view);
                                reportAdClick();
                            }
                        });
                    }
                }
            });
            startRequestTime = System.currentTimeMillis();
            RequestParameters requestParameters = new RequestParameters.Builder()
                    .downloadAppConfirmPolicy(RequestParameters.DOWNLOAD_APP_CONFIRM_ONLY_MOBILE)
                    .build();
            baidu.makeRequest(requestParameters);
            reportAdRequestVtwo();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MyMessageEvent event) {
        if(event.getNumber() == MyMessageEvent.USE_BAIDUCHECK_METHOD){
            if(mNativeResponse != null && mView != null){
                mNativeResponse.recordImpression(mView);
            }
        }
    };

    private void reportAdSuccess(){
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        gdtPropertyMap.put("result", "success");
        gdtPropertyMap.put("time", (System.currentTimeMillis()-startRequestTime)/1000+"");
        UmengEventPoster.doPost(UmengEventPoster.BAIDUAD_REQUEST, gdtPropertyMap);

        selfBaiduReport(SelfDataConstant.AC_ADREQUEST_SUCCESS);
    }

    private void reportAdRequestError(){
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        gdtPropertyMap.put("result", "fail");
        UmengEventPoster.doPost(UmengEventPoster.BAIDUAD_REQUEST, gdtPropertyMap);

        selfBaiduReport(SelfDataConstant.AC_ADREQUEST_FAIL);
    }

    private void reportAdError(int code){
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        gdtPropertyMap.put("code", code+"");
        UmengEventPoster.doPost(UmengEventPoster.BAIDUAD_ERROE, gdtPropertyMap);
    }

    private void reportAdShow() {
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        UmengEventPoster.doPost(UmengEventPoster.BAIDUAD_SHOW, gdtPropertyMap);

        selfBaiduReport(SelfDataConstant.AC_ADSHOW);
    }

    private void reportAdClick() {
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        UmengEventPoster.doPost(UmengEventPoster.BAIDUAD_CLICK, gdtPropertyMap);

        selfBaiduReport(SelfDataConstant.AC_ADCLICK);
    }

    private void reportAdClose() {
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        UmengEventPoster.doPost(UmengEventPoster.BAIDUAD_CLOSE, gdtPropertyMap);
    }

    private void reportAdRequestVtwo(){
        HashMap<String, String> gdtPropertyMap = new HashMap<>();
        gdtPropertyMap.put("position", mAdposition);
        UmengEventPoster.doPost(UmengEventPoster.BAIDUAD_REQUEST_VTWO, gdtPropertyMap);

        selfBaiduReport(SelfDataConstant.AC_SDKAD_REQUEST);
    }

    private void selfBaiduReport(String acode){
        MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
        record.setAcode(acode);
        record.setAd_pro(SelfDataConstant.AD_BD);
        record.setAd_po(mAdposition);
        RealmDaoManager.addMyDataRecord(record);
    }
}
